<?php
/**
 * Powered By ThinkPHP 5.0.12
 * Copyright (c) 2017 http://www.bojuwang.net All rights reserved.
 * Created by PhpStorm.
 * Date: 2018/5/2 0002
 * Time: 下午 3:53
 * Author: NanTao <260053530@qq.com>
 */
namespace app\api\controller;
use think\Controller;
use think\Request;
use think\Db;
class Wechat extends Controller
{
    protected $appid;
    protected $appsecret;
    public function _initialize()
    {
        parent::_initialize();
        $this->appid = sysconf('xwx_appid');
        $this->appsecret = sysconf('xwx_appsercet');
    }
    /**
     * 用户授权登录
     * @access public 
     * @param string $code(wx.login返回的code)
     * @date  2018-4-21
     */
    public function postUser(){
        $code = input('param.code');
        if (!$code) {
            json_msg(1, '请求错误');
        }

        $appid = $this->appid;
        $secret = $this->appsecret;
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $result = json_decode(request_get($url),true);
        $openid = $result['openid'];
        if(!$openid){
            json_msg(1,'openid获取失败');
        }
        $model = Db::name('user');
        $user_info = $model->where('wx_unionid',$result['unionid'])->find();
        if($user_info){
            if(!$user_info['xwx_openid']){
                Db::name('user')->where('id',$user_info['id'])->update(['xwx_openid'=>$openid]);
            }
            json_msg_data(0, 'ok', ['user_id' =>$user_info['id']]);
        }else{
            $data = [
                'user_name'=> get_user_username(),
                'xwx_openid'=>$openid,
                'wx_unionid' => $result['unionid']
            ];
            $userId = $model->insertGetId($data);   
            json_msg_data(0, 'ok', ['user_id' =>$user_info['id']]);
        }
    }

    /**
    * 修改用户信息
    * @access public 
    * @author  zhenbei
    * @param string $avatar 用户头像
    * @param string $nickName 用户昵称
    * @param string $user_id 用户id
    * @return json  返回信息
    * @date  2019-1-16
    */
    public function postUserinfo(){
        $avatar = input('param.avatarUrl');
        $nickName = input('param.nickName');
        if (!$avatar || !$nickName || !$user_id) {
            json_msg(1, '请求错误');
        }
        $data = [
            'user_nickname' => $nickName,
            'sex' => $userInfo['sex'],
            'avatar' => get_remote_img($avatar)
        ];
        $result = Db::name('user')->where('user_id',$user_id)->update($data);
        if ($result) {
            json_msg(0,'修改成功');
        }else{
            json_msg(1,'修改失败');
        }
    }
}